<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Pages extends MX_Controller 
{
	public function __construct()
	{
		parent::__construct();		
		$this->display->set_theme('cms');		
	}
	
	public function index()
	{	
		$this->load->model('page_model');
		$pages = $this->page_model->get(array('sort_by' => 'order'));
		$this->load->library('tree');
		$data['pages'] = $this->tree->rows_to_tree($pages, 'page_id', 'page_parent');		
		$this->twiggy->title()->append('Pages');
		$this->display->template('page_list', $data);
	}
	public function sort()
	{
	    $this->load->model('page_model');
        foreach($this->input->post('sortdata') as $index => $data)
        {
            if($data['item_id'] == NULL)
                continue;
           
            
            $this->page_model->update(array('page_id' => (int) $data['item_id'],
                                            'page_parent' => (int) ($data['parent_id'] == NULL ? 0 : $data['parent_id']),
                                            'order' => $index
                                            ));
            
            
        }
        $this->page_model->save_routes();
	}
	public function get_layout_widgets($layout_name)
	{
		$this->load->model('widget_model');
		$widgets = $this->widget_model->get();
		$areas = $this->display->get_layout_widget_areas($layout_name);
		$this->display->json_success(array('areas' => $areas, 'widgets' => $widgets));	
	}

	
	public function add()
	{
		// check permission
		//permission('cms', 'pages');
				
		// Validation
		$this->load->library('form_validation');	
		$this->form_validation->set_rules('page_parent', 'Page parent', 'required|integer');
		$this->form_validation->set_rules('page_name', 'Page name', 'required|callback_validate_name');
		$valid = $this->form_validation->run();				
		if($valid)
		{			
			$this->load->model('page_model');
			$this->load->model('content_model');
			$page_id = $this->page_model->insert(array('page_name' => $this->input->post('page_name'), 'page_created' => sql_current_datetime(), 'url' => url_title($this->input->post('page_name'))));
			if($page_id != FALSE)
				$this->content_model->insert(array('page_id' => $page_id, 'language' => $this->config->item('site_default_language')));
				
			$this->page_model->save_routes();
			flash_message('success', 'Page added');
		}
		else
		{
			flash_message('error', validation_errors());
		}
		cms_redirect('pages');
	}
	
	public function delete($id)
	{
		// check page id
		if(ctype_digit($id) == FALSE)
		{
			flash_message('error', 'Could not find the requested page');
			cms_redirect('dashboard');
		}
		
		// check permission
		//permission('cms', 'pages');
		
		$this->load->model('page_model');
		$this->load->model('content_model');
		
        // Page
		$this->page_model->delete(array('page_id' => $id));
        
        // Content
		$content = $this->content_model->get(array('page_id' => $id));
		if($content)
			foreach($content as $record)
				$this->content_model->delete(array('content_id' => $record['content_id']));

        
		$this->page_model->save_routes();
		flash_message('success', 'Page deleted');
		cms_redirect('pages');		
	}
	
	public function edit($id)
	{	
		// check page id
		if(ctype_digit($id) == FALSE)
		{
			flash_message('error', 'Could not find the requested page');
			cms_redirect('dashboard');
		}
		
		// check permission
		//permission('cms', 'pages');
		
		$this->load->model('page_model');
		$data = $this->page_model->get_page($id);		
		
		if($data)
		{		
			// On edit
			if($this->input->post())
			{
				// Validation
				$this->load->library('form_validation');	
							
				// create validaton rules based on languages
				foreach($data['used_languages'] as $lang)
				{
					// seo_keywords, seo_description, page_content
					$this->form_validation->set_rules($lang.'_seo_keywords', $lang.' SEO Keywords', 'max_length[255]');
					$this->form_validation->set_rules($lang.'_seo_description', $lang.' SEO Description', 'max_length[1000]');
				}
					
				$this->form_validation->set_rules('page_name', 'Page name', 'callback_validate_name');
				$this->form_validation->set_rules('page_parent', 'Page name', 'callback_validate_parent');
				
				$valid = $this->form_validation->run();
				
				// Widget / layout check
				$areas = $this->display->get_layout_widget_areas($this->input->post('layout'));
				if($areas == FALSE)
				{
					$this->form_validation->add_error('layout', 'Layout does not exists');
					$valid = FALSE;
				}				
				
				// Valid post data
				if($valid)
				{				
					// Contents
					$content_update = array();
					foreach($data['used_languages'] as $lang)
					{
						$content_update[$lang]['seo_keywords'] 			= $this->input->post($lang.'_seo_keywords');
						$content_update[$lang]['seo_description'] 		= $this->input->post($lang.'_seo_description');
						$content_update[$lang]['content']				= $this->input->post($lang.'_content');
					}
					
					$update = array();
					
					// Widgets
					$update['widgets'] = '';
					foreach($areas as $area)
					{
						$widget = $this->input->post($area);
						// Check if widget exists
						if(ctype_digit($widget))
                            $update['widgets'][$area] = (int) $widget;                                                  
					}
                    
					$update['widgets'] 								= json_encode($update['widgets']);
					
					// other stuff					
					$update['page_name'] 							= $this->input->post('page_name');
					$update['page_parent'] 							= $this->input->post('page_parent');
					$update['page_modified'] 						= sql_current_datetime();
					$update['url'] 									= url_title($update['page_name']);
					$update['page_id']								= $id;
					$update['layout']								= $this->input->post('layout');
					
                    // Check page parent, if this.page_parent == parent.page_parent
                    $new_parent = $this->page_model->get(array('page_id' => $update['page_parent']));
                    if($new_parent)
                    {
                        // If the user selects this page to be its own parrent (which is invalid)
                        if($update['page_parent'] == $id)
                        {
                            unset($update['page_parent']);                
                        }
                        // If the parent is currently the child, switch
                        if($new_parent['page_parent'] == $id)
                        {
                            $this->page_model->update(array('page_id' => $new_parent['page_id'], 'page_parent' => $data['page']['page_parent']));
                        }
                    }
                    
					// update content
					foreach($content_update as $language => $item)
					{
						$content_item = $this->content_model->get(array('page_id' => $id, 'language' => $language));
						$this->content_model->update(array('content_id' 		=> $content_item[0]['content_id'],
														   'seo_keywords' 		=> $item['seo_keywords'],
														   'seo_description' 	=> $item['seo_description'],
														   'page_content'		=> $item['content'],
														   'page_id'			=> $id));						
					}
					
					// Add / delete language? BUGGED!!!
					foreach($this->config->item('site_supported_languages') as $lang)
					{
						if($lang == $this->config->item('site_default_language')) // Do not touch the default language
							continue;
						
						if(in_array($lang, $this->input->post('languages'))) // User wants the language
						{
							if( ! in_array($lang, $data['used_languages'])) // do we already have the language? if not, create
							{
								$this->content_model->insert(array('page_id' => $id, 'language' => $lang));
							}
						}
						elseif(in_array($lang, $data['used_languages']))	// User does not want the language, lets delete it?
						{
							$content_item = $this->content_model->get(array('page_id' => $id, 'language' => $lang));
							$this->content_model->delete(array('content_id' => $content_item[0]['content_id']));									
						}
					}					
					
					// update pages
					if($this->page_model->update($update))
					{
						$this->page_model->save_routes();
						flash_message('success', 'Page has been edited');
						cms_redirect('pages/edit/'.$id);
					}					
				}
				else // post data not valid, redirect with validation errors
				{
					$data['message_type'] = 'error';
					$data['message'] = validation_errors();
				}
			}			
			
			// Show form
			$this->twiggy->title()->append('Edit page');
			$this->display->template('page_edit', $data);
		}
		else
		{
			flash_message('error', 'Could not find the requested page');
			cms_redirect('pages');
		}
	}
	
	public function validate_name($name)
	{
		$parent_id = $this->input->post('page_parent');
		if( ! ctype_digit($parent_id) )
		{
			$this->form_validation->set_message('validate_name', 'The %s field can not be the word "test"');
			return FALSE;		
		}
		
		$page = $this->page_model->get(array('page_name' => $name, 'page_parent' => $parent_id));
		if( ! $page )
		{
			$this->form_validation->set_message('validate_name', 'The %s field can not be the word "test"');
			return FALSE;
		}
			
		return TRUE;	
	}
	
	public function validate_parent($parent_id)
	{
		if( ! ctype_digit($parent_id) )
		{
			$this->form_validation->set_message('validate_parent', 'The %s field can not be the word "test"');
			return FALSE;
		}
		
		$page = $this->page_model->get(array('page_id' => $parent_id));
		if( ! $page )
		{
			$this->form_validation->set_message('validate_parent', 'The %s field can not be the word "test"');
			return FALSE;
		}
		
		return TRUE;
	}

	private function _save_route($id)
	{
		
	}
	
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */